package controller

import (
	"bytes"
	"crypto/md5"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"gdfs-center/controller/ao"
	"gdfs-center/db"
	"gdfs-center/err"
	"gdfs-center/logcat"
	"github.com/gin-gonic/gin"
	"math/big"
	"strconv"
	"time"
)

//创建节点
func CreateNode(c *gin.Context) {
	c.Writer.Header().Set("content-type", "application/json")
	var ao ao.CreateNodeAo
	jsonerr := json.Unmarshal(GetPostJson(c.Request), &ao)
	if jsonerr != nil {
		logcat.GetLog().Sugar().Info("###jsonerr:", jsonerr)
		WritedString(c.Writer, false, err.JSONERR, err.Errortype[err.JSONERR], nil)
		return
	}
	if ao.NodeName == "" {
		WritedString(c.Writer, false, err.NOTVALID_ERROR, err.Errortype[err.NOTVALID_ERROR], nil)
		return
	}
	if ao.Remark == "" {
		WritedString(c.Writer, false, err.NOTVALID_ERROR, err.Errortype[err.NOTVALID_ERROR], nil)
		return
	}
	var node db.Node
	db.GetDB().Where("node_name = ?", ao.NodeName).First(&node)
	if node != (db.Node{}) {
		WritedString(c.Writer, false, err.DUPLICATE, err.Errortype[err.DUPLICATE], nil)
		return
	}
	//生成nodeid并存入数据库
	signtemp := strconv.FormatInt(time.Now().UnixNano(), 10) + CreateRandomString(8)
	sgin := md5.Sum([]byte(signtemp))
	nodeid := hex.EncodeToString(sgin[:])
	node.NodeName = ao.NodeName
	node.Remark = ao.Remark
	node.NodeId = nodeid
	db.GetDB().Create(&node)
	WritedString(c.Writer, true, err.SUCESS, err.Errortype[err.SUCESS], nil)
}

func CreateRandomString(len int) string {
	var container string
	var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
	b := bytes.NewBufferString(str)
	length := b.Len()
	bigInt := big.NewInt(int64(length))
	for i := 0; i < len; i++ {
		randomInt, _ := rand.Int(rand.Reader, bigInt)
		container += string(str[randomInt.Int64()])
	}
	return container
}
